package com.herr.springboot.self.xxx.config;

import com.herr.springboot.self.xxx.common.extend.HeaderInterceptor;
import com.herr.springboot.self.xxx.common.extend.PrincipalResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 提供mvc相关的静态资源映射、拦截器、参数解析器、VC添加等
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${application.swagger.showui:true}")
    private boolean showui;

    @Autowired
    private HeaderInterceptor headerInterceptor;

    @Autowired
    private PrincipalResolver principalResolver;

    /**
     * 静态资源映射器
     * @param registry
     */
    @Override
    public  void addResourceHandlers(ResourceHandlerRegistry registry) {

        // 由于spring.resources.add-mappings为false，spring会关闭自动映射。如需要使用静态资源，在此添加映射
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        // 添加swagger静态资源映射，如是生产环境，自动不添加。
        if (showui) {
            registry.addResourceHandler("swagger-ui.html")
                    .addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

    /**
     * 注册拦截器，用于controller前鉴权、日志等处理
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(headerInterceptor)
        .addPathPatterns("/**")
        .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**","/error","/");
    }

    /**
     * 注册参数解析器
     * @param resolvers
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(principalResolver);
    }

    /**
     * 添加首页跳转
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:static/index.html");
    }
}
